# encoding: utf-8
# @File  : cache.py
# @Author: shaoyun
# @Date  :  2025/05/11
from functools import wraps
from typing import Callable, Any
import time

def cache_decorator(ttl: int = 60):
    """
    缓存装饰器，用于缓存函数结果。
    :param ttl: 缓存的有效时间（秒）
    """
    def decorator(func: Callable) -> Callable:
        cache = {}

        @wraps(func)
        async def wrapper(*args, **kwargs) -> Any:
            # 生成缓存的唯一键
            key = str(args) + str(kwargs)
            now = time.time()

            # 检查缓存是否存在且未过期
            if key in cache:
                result, timestamp = cache[key]
                if now - timestamp < ttl:
                    return result

            # 调用原函数并缓存结果
            result = await func(*args, **kwargs)
            cache[key] = (result, now)
            return result

        return wrapper
    return decorator